package com.stenio.fancat.service.wx;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.shop.FcEtOrder;
import com.stenio.fancat.domain.shop.FcEtOrderLog;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.mapper.shop.FcEtOrderLogMapper;
import com.stenio.fancat.mapper.user.UserRelationshipMapper;
import com.stenio.fancat.mapper.wx.FcEtOrderMapper;
import com.stenio.fancat.payment.PayMent;
import com.stenio.fancat.util.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liuan
 * @create 2019-02-26 16:25
 */

@Service
public class FcEtOrderService extends ServiceImpl<FcEtOrderMapper, FcEtOrder> {

    @Autowired
    private PayMent payMent;

    @Autowired
    private FcEtOrderLogMapper fcEtOrderLogMapper;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    public Integer extractAmount(String id,String babyId) throws FanCatException {
        UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(id);
        List<FcEtOrder> fcEtOrders = baseMapper.selectList(new EntityWrapper<FcEtOrder>().eq(FcEtOrder.USER_ID, id)
                .eq(FcEtOrder.STATUS,1)
                .eq(FcEtOrder.BABY_ID,babyId)
                .ne(FcEtOrder.REFLECT_AMOUNT,0));
        Integer total = 0;
        for (FcEtOrder fcEtOrder : fcEtOrders) {
            total += fcEtOrder.getReflectAmount();
        }
        if(total < 1000) {
            throw new FanCatException("红包余额不足10元,无法提现");
        }
        Integer withMoney = (int)Math.floor(total - total*0.01);
        Map<String, String> resultMap = payMent.sendWallet(userRelationship.getOpenId(), withMoney, "红包提现");
        if(EmptyUtil.isEmpty(resultMap)) {
            throw new FanCatException("红包提现失败");
        }
        FcEtOrder fcEtOrder = new FcEtOrder();
        fcEtOrder.setReflectAmount(0);
        for (FcEtOrder etOrder : fcEtOrders) {
            baseMapper.update(fcEtOrder,new EntityWrapper<FcEtOrder>().eq(FcEtOrder.OUT_TRADE_NO,etOrder.getOutTradeNo()));
        }
        FcEtOrderLog fcEtOrderLog = new FcEtOrderLog();
        fcEtOrderLog.setFee(withMoney);
        fcEtOrderLog.setUserId(id);
        fcEtOrderLog.setBabyId(babyId);
        fcEtOrderLog.setCreateTime(new Date());
        fcEtOrderLog.setUpdateTime(new Date());
        fcEtOrderLogMapper.insert(fcEtOrderLog);
        return withMoney;
    }

}
